﻿using System.Windows;
using System.Windows.Navigation;
using $safeprojectname$.Home;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Autofac;
using Columbus;
using $safeprojectname$.Infrastructure;

namespace $safeprojectname$
{
    public partial class App
    {
        public PhoneApplicationFrame RootFrame { get; private set; }

        public App()
        {
            UnhandledException += ApplicationUnhandledException;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Current.Host.Settings.EnableFrameRateCounter = true;
            }

            InitializeComponent();

            InitializePhoneApplication();

            var container = InitializeContainer();

            InitializeColumbus(container);
        }

        private static IContainer InitializeContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new NavigationModule());
            builder.RegisterModule(new HomeModule());

            return builder.Build();
        }

        private void InitializeColumbus(IComponentContext container)
        {
            var navApp = container.Resolve<NavigationAppication>();
            PhoneApplicationService.Current.Activated += navApp.Activated;
            RootFrame.Navigated += navApp.StatusChanged;
        }

        private static void RootFrameNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
        }

        private static void ApplicationUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
        }

        private bool phoneApplicationInitialized;

        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            RootFrame.NavigationFailed += RootFrameNavigationFailed;

            phoneApplicationInitialized = true;
        }

        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            RootVisual = RootFrame;
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

    }
}